<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\Carbarn;
use App\Observers\CarbarnObserver;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        \Carbon\Carbon::setLocale('zh');
        \Illuminate\Support\Facades\Schema::defaultStringLength(191);
        $this->logSql();
        $this->listenORMEvents();
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(\Faker\Generator::class, function() {
            return \Faker\Factory::create('zh_CN');
        });
    }

    private function logSql()
    {
        \DB::listen(function($query) {
            $log = sprintf(
                "%s, sql: %s, bindngs: %s, timeuse: %sms %s",
                date('Y-m-d H:i:s'),
                $query->sql,
                json_encode($query->bindings, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),
                $query->time,
                PHP_EOL
            );
            file_put_contents(storage_path() . '/logs/sql.log', $log, FILE_APPEND);
        });
    }

    private function listenORMEvents()
    {
        Carbarn::observe(CarbarnObserver::class);
    }
}
